package com.mo.config.handler;


import com.mo.constant.Constants;
import com.mo.model.TUser;
import com.mo.result.R;
import com.mo.util.JSONUtils;
import com.mo.util.JWTUtils;
import com.mo.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功，执行该方法，在该方法中返回json给前端，就行了
        //这里的tUser是UserDetailsService的loadUserByUsername方法实现的返回的结果
        TUser tUser = (TUser) authentication.getPrincipal();
        //1、生成jwt
        //把tUser对象转成json作为负载数据放入jwt
        String userJSON = JSONUtils.toJSON(tUser);
        String jwt = JWTUtils.createJWT(userJSON);

        String key=Constants.REDIS_JWT_KEY+tUser.getId();

        stringRedisTemplate.opsForValue().set(key,jwt);



        if (Boolean.parseBoolean(request.getParameter("rememberMe"))){
            stringRedisTemplate.expire(key,Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        }else {
            stringRedisTemplate.expire(key,Constants.DEFAULT_EXPIRE_TIME,TimeUnit.SECONDS);
        }



        //登录成功的统一结果
        R result = R.OK(jwt);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把R以json返回给前端
        ResponseUtils.write(response, resultJSON);
    }
}
